package com.tqz.juc.sentinel;

import lombok.SneakyThrows;

import java.util.LinkedList;
import java.util.Random;

/**
 * <p>
 *
 * @author tianqingzhao
 * @since 2022/2/28 20:30
 */
public class RollingWindowTest {
    
    Long counter = 0L;
    LinkedList<Long> slots = new LinkedList<>();
    
    public static void main(String[] args) throws InterruptedException {
        RollingWindowTest rollingWindowTest = new RollingWindowTest();
        
        new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                rollingWindowTest.doCheck();
            }
        }).start();
        
        while (true) {
            rollingWindowTest.counter++;
            Thread.sleep(new Random().nextInt(50));
            
        }
    }
    
    private void doCheck() throws InterruptedException {
        while (true) {
            Thread.sleep(100);
            slots.addLast(counter);
            if(slots.size() > 10) {
                slots.removeFirst();
            }
            
            if (slots.peekLast() - slots.peekFirst() > 100) {
                System.out.println("限流。。。");
            } else {
                System.out.println("没有限流。。。");
            }
        }
    
    }
    
}
